﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Globalization;
using System.Reflection;

namespace CochinitaCorte//.CochinitaCorteData
{   
    public static class FileManager
    {

        public static string[] ReadFile(string FullFileName)
        {
            var reader = new StreamReader(File.OpenRead(@FullFileName));
           
            string data = reader.ReadToEnd();
            data = data.Replace("\n", "");
            string[] Alldata = data.Split('\r');
                       
            return Alldata;
         }

        public static string ReadFile(string FullFileName, string dummy)
        {
            var reader = new StreamReader(File.OpenRead(@FullFileName));

            return  reader.ReadToEnd();
        }

        public static bool WriteToFile(string FullFileName, string FileContent)
        {
            try
            {
                System.IO.StreamWriter file = new System.IO.StreamWriter(FullFileName);

                file.WriteLine(FileContent);
                file.Close();

            }
            catch (IOException ex)
            {
                //ExceptionsThrown(ex, FileName);
                return false;
            }
            return true;
        }
        private static string FileNameBuilder( )
        {
            string FileName = "";
           
            FileName = @"\USUARIOS_";
            
            FileName += DateTime.Now.ToString("yyyyMMddHHmm", new CultureInfo("es-MX", true)) + ".txt";

            return FileName;
        }
       
        public static string CreateCSVFile<T>(string FilePath, IEnumerable<T> objectlist)
        {
            string results;

            results = ConvertObjectToCSV(",", objectlist);

            string FileName = FilePath + FileNameBuilder();
            if (WriteToFile(FileName, results))
            {
                return FileName;
            }
            else

                return "";
        }

        private static string ConvertObjectToCSV<T>(string delimiter, IEnumerable<T> objectlist)
        {
            FieldInfo[] fields = typeof(T).GetFields();
            PropertyInfo[] properties = typeof(T).GetProperties();
            string buffer = "";

            foreach (var o in objectlist)
            {
                buffer = buffer + (buffer == string.Empty ? "" : "\r\n") + string.Join(delimiter, properties.Select(p => (p.GetValue(o, null) ?? "").ToString()));
            }
            return buffer;
        }

        public static bool FileExist(string FullFileName)
        {
           return File.Exists(FullFileName);
        }
    }
}
